import {  Modal ,Input} from 'antd';
import { useState } from 'react';
import UploadAvatar from "./upload"
import { UserOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { update } from "@/api/service/userService"
import { message } from "antd";

export default function Edit() {
    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [avatarFile, setAvatarFile] = useState() // 状态用来存储选中的头像文件
    const [messageApi, contextHolder] = message.useMessage();

    const userInfo=useSelector((state:any)=>state.user.userInfo)
  
    const showModal = () => {
      setOpen(true);
    };

    // 定义回调函数，用来接收选中的头像文件
    const handleFileChange = (file:any) => {
        setAvatarFile(file);
    }
  

  const handleOk = () => {
        setConfirmLoading(true);
         // 进行接口请求
        if(!avatarFile){
          message.warning('请选择要修改的头像');
          setConfirmLoading(false); 
        }
        else{
        update(avatarFile).then(val => {
       // 修改成功给提示信息
       messageApi.open({
        type: 'success',
        content: '修改头像成功！',
      })
      setConfirmLoading(false); // 修改成功后退出加载状态
      setOpen(false); // 可以根据需求设置是否关闭模态框
    }).catch(err => {
      // 修改失败给提示信息
      messageApi.open({
        type: 'error',
        content: err.message,
      });
      setConfirmLoading(false);
    })       
    }
  }

    const handleCancel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
      };
    const titleStyle={
        fontSize:16,
        margin:10,
        marginTop:30
    }
      

    return (
        <>
             {/* 提示框 */}
            {contextHolder}
            <div onClick={showModal}>修改个人信息</div>
            <Modal
                title="修改个人信息"
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
            >
                <h1 style={titleStyle}>用户名</h1>
                <Input size="large" disabled placeholder="填写用户名称" value={userInfo.username} prefix={<UserOutlined />} />
                <h1 style={titleStyle}>用户头像</h1>
                <UploadAvatar onFileChange={handleFileChange}/>
            </Modal>
        </>
    )
}